package naga.x.platform2.channel.wanba;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qq.open.ErrorCode;

import naga.x.platform2.app.Channel;
import naga.x.platform2.app.model.Recharge;
import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.app.support.RechargeSupport;
import naga.x.platform2.channel.wanba.support.QZoneApi;
import naga.x.platform2.channel.wanba.support.QZoneConfig;
import naga.x.platform2.support.RequestPath;
import naga.x.platform2.utils.PlatformUtils;
import naga.x.platform2.utils.StringUtils;

/**
 * 玩吧
 * @see <a href="http://wiki.open.qq.com/wiki/API%E5%88%97%E8%A1%A8">腾讯开放平台</a>
 * @see <a href="http://qzs.qzone.qq.com/qzone/qzact/act/game/wanba/wiki.html">QQ空间·玩吧</a>
 * @see <a href="https://open.mobile.qq.com/api/h5plus/index#api">腾讯移动WEB开发平台</a>
 * @author yang.li
 *
 */
@Controller
public class QZoneController {
	
	@Autowired
	private QZoneConfig config;
	@Autowired
	private RechargeSupport support;
	
	private static Channel channel = Channel.QQ_WANBA;
	
	private static final Logger LOG = LoggerFactory.getLogger(QZoneController.class);

	/**
	 * 充值（购买钻石）
	 * @param sid
	 * @param pid
	 * @param openid
	 * @param openkey
	 * @param product
	 * @param zoneid
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_PAY, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object pay(Integer sid, Long pid, String openid, String openkey, Integer product, @RequestParam(required = false) String zoneid) {
//		http://openapi.tencentyun.com/v3/user/buy_playzone_item?
//			openid=B624064BA065E01CB73F835017FE96FA&
//			zoneid=1&
//			openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C&
//			appid=2&
//			itemid=10&
//			count=1&
//			sig=VrN%2BTn5J%2Fg4IIo0egUdxq6%2B0otk%3D&
//			pf=qzone&
//			format=json&
//			userip=112.90.139.30
//		RechargeTemplate template = App.getRechargeTemplate(product);
		LOG.info("[QZONE PAYING]SERVER[{}]PLAYER[{}]PRODUCT[{}]OPENID[{}]ZONE[{}]", sid, pid, product, openid, zoneid);
		RechargeTemplate template = support.getTemplate(product);
		if (template == null) {
			return QZoneApi.newError(ErrorCode.PARAMETER_INVALID, "充值id错误");
		}
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		zoneid = QZoneApi.ZONEID_ANDROID.equals(StringUtils.trim(zoneid)) ? QZoneApi.ZONEID_ANDROID : QZoneApi.ZONEID_IOS;
		params.put("zoneid", zoneid);
		params.put("itemid", String.valueOf(config.getRechargeItemByProduct(zoneid, product)));
		params.put("count", "1");
//		{
//			"code":0,
//			"subcode":0,
//			"message":"",
//			"default":0,
//			"data":
//			[{
//			"billno":1234,
//			"cost":"1000"
//			}]
//			}
		
		JSONObject res = QZoneApi.invoke("/v3/user/buy_playzone_item", params);
		if (res == null) {
			return QZoneApi.newError(ErrorCode.NETWORK_ERROR, "网络错误");
		}
		Integer code = res.getInteger("code");
		if (code == null) {
			code = res.getInteger("ret");
		}
		boolean succ = false;
		if (code != null && code == QZoneApi.CODE_SUCC) {
			JSONArray datas = res.getJSONArray("data");
			JSONObject data = datas.getJSONObject(0);
			String orderId = data.getString("billno");
			int cost = data.getIntValue("cost");
			int money = template.getPrice();
			Recharge recharge = new Recharge(channel.prefix + orderId, pid, sid, money, cost, product, channel.name);
			succ = support.offer(recharge);
		}
		LOG.info("[QZONE {}]PARAMS[{}]RES[{}]", succ ? "PAIED" : "PAY FAIL", params, res);
		return res;
	}
	
	/**
	 * 获取用户信息
	 * @param openid
	 * @param openkey
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_USER_INFO, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object getUserInfo(String openid, String openkey) {
		HashMap<String, String> params = new HashMap<String, String>(2);
		params.put("openid", openid);
		params.put("openkey", openkey);
		JSONObject res = QZoneApi.invoke("/v3/user/get_info", params);
		if (res != null) {
			String icon = PlatformUtils.mappingIcon(channel, res.getString("figureurl"));
			if (icon != null) {
				res.put("figureurl", icon);
			}
		}
		return res;
	}
	
	/**
	 * 获取用户达人信息
	 * @param openid
	 * @param openkey
	 * @param zoneid
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_PLAYZONE_USERINFO, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object getPlayzoneUserInfo(String openid, String openkey, @RequestParam(required = false) String zoneid) {
//		http://openapi.tencentyun.com/v3/user/get_playzone_userinfo?
//			openid=B624064BA065E01CB73F835017FE96FA&
//			zoneid=1&
//			openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C&
//			appid=2&
//			sig=VrN%2BTn5J%2Fg4IIo0egUdxq6%2B0otk%3D&
//			pf=qzone&
//			format=json&
//			userip=112.90.139.30
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		params.put("zoneid", StringUtils.isEmpty(zoneid) ? QZoneApi.ZONEID_ANDROID : zoneid);
		return QZoneApi.invoke("/v3/user/get_playzone_userinfo", params);
	}
	
	/**
	 * 验证用户登录态&Openkey续期
	 * @param openid
	 * @param openkey
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_CHECK_LOGIN, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object checkLogin(String openid, String openkey) {
//		http://113.108.20.23/v3/user/is_login?
//			openid=B624064BA065E01CB73F835017FE96FA&
//			openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C&
//			appid=2&
//			sig=9999b41ad0b688530bb1b21c5957391c&
//			pf=qzone&
//			format=json&
//			userip=112.90.139.30
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		return QZoneApi.invoke("/v3/user/is_login", params);
	}
	
	/**
	 * 获取好友列表（玩过游戏的好友）
	 * @param openid
	 * @param openkey
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_FRIENDS, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object getFriends(String openid, String openkey) {
//		https://api.urlshare.cn/v3/relation/get_app_friends?
//			openid=B624064BA065E01CB73F835017FE96FA&
//			openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C&
//			appid=2&
//			sig=9999b41ad0b688530bb1b21c5957391c&
//			pf=wanba_ts&
//			format=json&
//			userip=112.90.139.30
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		return QZoneApi.invoke("/v3/relation/get_app_friends", params);
	}
	
	/**
	 * 批量获取用户信息
	 * @param openid
	 * @param openkey
	 * @param openids
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_MULTI_USER_INFO, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object batchGetUsers(String openid, String openkey, String[] openids) {
//		https://api.urlshare.cn/v3/user/get_multi_info?
//			openid=08B8273AAAABE0D9F84CAB4E8888DAA0&
//			openkey=9999996917C28878F66F28E7F16B7F89E7E752D589B8B261&
//			appid=2&
//			sig=9999b41ad0b688530bb1b21c5957391c&
//			pf=wanba_ts&
//			format=json&
//			userip=112.90.139.30&
//			fopenids=08B9999CACFBE0D9F57CAB4E7D8BDBF0_83A390F6A8E66BA800829ECD6032A6DE
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		params.put("fopenids", QZoneApi.wrapOpenIds(openids));
		return QZoneApi.invoke("/v3/user/get_multi_info", params);
	}
	
	/**
	 * 上报积分
	 * @param openid
	 * @param openkey
	 * @param data
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_SET_ACHIEVEMENT, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object setAchievements(String openid, String openkey, String data) {
//		https://api.urlshare.cn/v3/user/set_achievement?
//			openid=B624064BA065E01CB73F835017FE96FA&
//			openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C&
//			appid=2&
//			pf=wanba_ts&
//			format=json&
//			userip=112.90.139.30&
//			user_attr=%7B%22level%22%3A10%7D&
//			sig=9999b41ad0b688530bb1b21c5957391c
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		params.put("user_attr", data);
		return QZoneApi.invoke("/v3/user/set_achievement", params);
	}
	
	/**
	 * 拉取排行榜
	 * @param openid
	 * @param openkey
	 * @param type
	 * @param offset
	 * @param count
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_RANKING_LIST, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object getRankingList(String openid, String openkey, String type, int offset, int count) {
//		https://api.urlshare.cn/v3/user/get_gamebar_ranklist?
//			openid=B624064BA065E01CB73F835017FE96FA&
//			openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C&
//			appid=307653887&
//			dimname=level&
//			rank_start=0&
//			pull_cnt=10&
//			direction=1&
//			sig=VrN%2BTn5J%2Fg4IIo0egUdxq6%2B0otk%3D&
//			pf=wanba_ts&
//			format=json&
//			userip=112.90.139.30
//		dimname	是	string	拉取纬度，类别一对应level，类别二对应key1，类别三对应key2
//		rank_start	否	int	拉取排行的起始位置（默认0）
//		pull_cnt	否	int	拉取排行的个数（最小为3，最大为50，默认3）
//		direction	否	int	拉取排行的方向（-1往前拉取，0向后拉取，默认0）
		if (offset < 0) {
			offset = 0;
		}
		if (count < 3) {
			count = 3;
		} else if (count > 50) {
			count = 50;
		}
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		params.put("dimname", type);
		params.put("rank_start", String.valueOf(offset));
		params.put("pull_cnt", String.valueOf(count));
		params.put("direction", "0");
		return QZoneApi.invoke("/v3/user/get_gamebar_ranklist", params);
	}
	
	/**
	 * 向好友发送消息
	 * @param openid
	 * @param openkey
	 * @param fopenid
	 * @param type
	 * @param content
	 * @param client 手机客户端标识
	 * @return
	 */
	@RequestMapping(path = RequestPath.QZONE_SEND_MSG, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object sendMessage(String openid, String openkey, String fopenid, String type, String content, String client) {
//		https://api.urlshare.cn/v3/user/send_gamebar_msg?
//			openid=B624064BA065E01CB73F835017FE96FA&
//			zoneid=1&
//			openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C&
//			appid=2&qua=V1_AND_QZ_4.9.3_148_RDM_T&
//			frd=2CEAEF4CBCB87DC6C1AF122E1A260EA8&msgtype=2&content=12秒&
//			sig=VrN%2BTn5J%2Fg4IIo0egUdxq6%2B0otk%3D&
//			pf=wanba_ts&
//			format=json&
//			userip=112.90.139.30
//		frd	是	string	好友openid
//		msgtype	是	int	消息类型，1-pk消息，2-送心消息，3-自定义消息
//		content	是	string	自定义消息内容
//		qua	是	string	手机客户端标识，例如：V1_AND_QZ_4.9.3_148_RDM_T
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("openkey", openkey);
		params.put("frd", fopenid);
		params.put("msgtype", type);
		params.put("content", content);
		params.put("qua", client != null ? client : "V1_AND_QZ_4.9.3_148_RDM_T");
		return QZoneApi.invoke("/v3/user/send_gamebar_msg", params);
	}
	
}
